package it.eng.area118.mdogpscollector.fragment;

import it.eng.area118.mdocommon.geolocation.GpsLocation;
import it.eng.area118.mdogpscollector.R;
import it.eng.area118.mdogpscollector.listener.FragmentActionReceiver;
import it.eng.area118.mdogpscollector.listener.ManageCheckPointListener;
import it.eng.area118.mdogpscollector.model.CheckPoint;
import it.eng.area118.mdogpscollector.service.CheckPointLookupService;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class CheckpointDetailFragment extends Fragment {

	private CheckPoint cp;

	private ManageCheckPointListener listener;

	private View rootView;

	private AtomicReference<GpsLocation> location;

	public static final String CHECKPOIN_ID = "CHECKPOIN_ID";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.location = new AtomicReference<GpsLocation>(null);
		if (getArguments() != null)
			if (getArguments().containsKey(CHECKPOIN_ID)) {
				String checkPointId = getArguments().getString(CHECKPOIN_ID);
				List<CheckPoint> cpList = CheckPointLookupService.getService().lookup(checkPointId, null);
				cp = cpList.get(0);

			}
		listener.onStartCoordCapture();
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (!(activity instanceof FragmentActionReceiver<?>)) {
			throw new IllegalStateException("Activity must implement fragment's callbacks.");
		}

		FragmentActionReceiver receiver = (FragmentActionReceiver) activity;
		listener = (ManageCheckPointListener) receiver.getActionListener();
		Log.i("CheckPointListFragment", "onAttach");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_checkpoint_detail, container, false);
		if (cp != null) {
			((TextView) rootView.findViewById(R.id.title)).setText(cp.toString());
			((TextView) rootView.findViewById(R.id.coordDetail)).setText(cp.getCoordDetail());
		}
		checkLocationStyle();
		initSaveBtListener();
		return rootView;
	}

	private void checkLocationStyle() {
		TextView tv = ((TextView) rootView.findViewById(R.id.coordDetail));
		if (tv != null) {
			if (cp != null && cp.getLocation() == null) {
				tv.setBackgroundResource(R.drawable.border_no_fill);
			} else {
				tv.setBackgroundResource(R.drawable.border_fill);
			}

		}

	}

	private void initSaveBtListener() {
		Button bt = (Button) rootView.findViewById(R.id.bt_update_check_point);
		bt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				listener.onStopCoordCapture();
				it.eng.area118.mdogpscollector.model.GpsLocation loc = checkAndCopyLocation();
				if (loc != null) {
					cp.setLocation(loc);
				}
				;
				listener.onSaveCheckPointCoord(cp);
			}
		});

	}

	public void updateCurrentLocation(GpsLocation location) {
		if (this.location == null) {
			return;
		}

		this.location.set(location);
		((TextView) rootView.findViewById(R.id.title)).setText(cp.toString());
		if (cp.getLocation() == null) {
			((TextView) rootView.findViewById(R.id.coordDetail)).setText(stringifyLocation());
		} else {
			((TextView) rootView.findViewById(R.id.coordDetail)).setText(cp.getCoordDetail());
		}
		checkLocationStyle();

	}

	public it.eng.area118.mdogpscollector.model.GpsLocation checkAndCopyLocation() {
		if (this.location.get() == null) {
			return null;
		}
		it.eng.area118.mdogpscollector.model.GpsLocation loc = new it.eng.area118.mdogpscollector.model.GpsLocation();
		GpsLocation currLoc = this.location.get();
		loc.setAccuracy(currLoc.getAccuracy());
		loc.setBearing(currLoc.getBearing());
		loc.setLatitude(currLoc.getLatitude());
		loc.setLongitude(currLoc.getLongitude());
		loc.setSatNumber(currLoc.getSatNumber());
		loc.setSpeed(currLoc.getSpeed());
		loc.setTimestamp(currLoc.getTimestamp());
		return loc;
	}

	public void updateContent() {
		((TextView) rootView.findViewById(R.id.title)).setText(cp.toString());
		((TextView) rootView.findViewById(R.id.coordDetail)).setText(cp.getCoordDetail());
		checkLocationStyle();

	}

	public void setCheckPoint(CheckPoint result) {
		if (result == null) {
			return;
		}
		cp = null;
		this.cp = result;
		((TextView) rootView.findViewById(R.id.title)).setText(cp.toString());
		it.eng.area118.mdogpscollector.model.GpsLocation loc = cp.getLocation();
		if (loc != null) {
			((TextView) rootView.findViewById(R.id.coordDetail)).setText(cp.getCoordDetail());
		}
		checkLocationStyle();

	}

	private String stringifyLocation() {
		StringBuffer buffer = new StringBuffer();
		if (this.location.get() != null) {

			DateFormat format = SimpleDateFormat.getDateTimeInstance();
			Calendar c = Calendar.getInstance();
			c.setTimeInMillis(this.location.get().getTimestamp());
			buffer.append(format.format(c.getTime()));
			buffer.append("\n");
			buffer.append("Latitudine: " + this.location.get().getLatitude());
			buffer.append("\n");
			buffer.append("Longitudine: " + this.location.get().getLongitude());
			buffer.append("\n");
			buffer.append("Accuratezza: " + this.location.get().getAccuracy());
			buffer.append("\n");
			buffer.append("Numero Satelliti: " + this.location.get().getSatNumber());
		}
		return buffer.toString();
	}
}
